package com.auxgroup.hr.front.service.performance.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.auxgroup.hr.front.commons.enums.WfStatusEnum;
import com.auxgroup.hr.front.commons.enums.WfTypeEnum;
import com.auxgroup.hr.front.commons.utils.ObjectFieldUtils;
import com.auxgroup.hr.front.commons.utils.WebServiceClient;
import com.auxgroup.hr.front.commons.utils.WebServiceUtils;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dao.domain.JobCurrPrimary;
import com.auxgroup.hr.front.dao.domain.PsCEpAppHdr;
import com.auxgroup.hr.front.dao.domain.PsCEpAppHdrPrimary;
import com.auxgroup.hr.front.dao.domain.PsCEpAppRVw2;
import com.auxgroup.hr.front.dao.domain.PsCEpAppRstVw;
import com.auxgroup.hr.front.dao.domain.PsCEpAppRstVwPrimary;
import com.auxgroup.hr.front.dao.domain.PsCEpIntrvwTbl;
import com.auxgroup.hr.front.dao.domain.PsCEpMdlgradeV;
import com.auxgroup.hr.front.dao.domain.PsCEpMdlgradeVPrimary;
import com.auxgroup.hr.front.dao.domain.PsCEpRankGpVw;
import com.auxgroup.hr.front.dao.domain.PsCEpTmplNmVw;
import com.auxgroup.hr.front.dao.domain.PsCEpTrvRole;
import com.auxgroup.hr.front.dao.domain.PsCWfApelHdr;
import com.auxgroup.hr.front.dao.domain.PsCWfEmpVw;
import com.auxgroup.hr.front.dao.repository.PsCEpAppHdrRepository;
import com.auxgroup.hr.front.dao.repository.PsCEpAppRVw2Repository;
import com.auxgroup.hr.front.dao.repository.PsCEpAppRstVwRepository;
import com.auxgroup.hr.front.dao.repository.PsCEpIntrvwTblRepository;
import com.auxgroup.hr.front.dao.repository.PsCEpMdlgradeVRepository;
import com.auxgroup.hr.front.dao.repository.PsCEpRankGpVwRepository;
import com.auxgroup.hr.front.dao.repository.PsCEpTmplNmVwRepository;
import com.auxgroup.hr.front.dao.repository.PsCEpTrvRoleRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfApelHdrRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfEmpVwRepository;
import com.auxgroup.hr.front.dozer.IObjectMapper;
import com.auxgroup.hr.front.service.performance.PerformanceResultService;
import com.auxgroup.hr.front.ws.SoapXmlBuild;

/** 
 * @author lvliuhao 
 * @version 创建时间：2018年9月10日 下午2:18:18 
 * 类说明 
 */
@Service(value="performanceResultService")
public class PerformanceResultServiceImpl implements PerformanceResultService {
	
	@Autowired
	private PsCEpAppRstVwRepository psCEpAppRstVwRepository;
	
	@Autowired
	private PsCEpAppHdrRepository psCEpAppHdrRepository;
	
	@Autowired
	private PsCEpMdlgradeVRepository psCEpMdlgradeVRepository;
	
	@Autowired
	private PsCWfApelHdrRepository psCWfApelHdrRepository;

	@Autowired
	private PsCWfEmpVwRepository psCWfEmpVwRepository;
	
	@Autowired
	private PsCEpTmplNmVwRepository psCEpTmplNmVwRepository;
	
	@Autowired
	private PsCEpRankGpVwRepository psCEpRankGpVwRepository;
	
	@Autowired
	private PsCEpIntrvwTblRepository psCEpIntrvwTblRepository;
	
	@Autowired
	private PsCEpTrvRoleRepository psCEpTrvRoleRepository;
	
	@Autowired
	private PsCEpAppRVw2Repository psCEpAppRVw2Repository;
	
	@Resource(name = "dozerMapper")
	protected IObjectMapper objectMapper;
	
	@Value("${ws.processService.approve.address}")
	private String processURL;
	
	@Value("${ws.processService.epIntrvwReq.soapAction}")
	private String intrvwReqSoapAction;

	@Override
	public List<PsCEpAppRstVw> getResultList(String oprid, String year) {
		PsCEpAppRstVw query = new PsCEpAppRstVw();
		query.setOprid(oprid);
		query.setYear(year);
		return psCEpAppRstVwRepository.findAll(Example.of(query));
	}



	@Override
	public PsCEpAppHdr getAppHdr(String docid, BigDecimal version) {
		PsCEpAppHdrPrimary primary = new PsCEpAppHdrPrimary();
		primary.setcEpAppraisalId(docid);
		primary.setVersion(version);
		return psCEpAppHdrRepository.findOne(primary);
	}



	@Override
	public PsCEpMdlgradeV getMdlGrade(String model, String grade) {
		PsCEpMdlgradeVPrimary primary = new PsCEpMdlgradeVPrimary();
		primary.setcEvaGrade(grade);
		primary.setcEvaModel(model);
		return psCEpMdlgradeVRepository.findOne(primary);
	}


	@Override
	public PsCEpAppHdr saveAppHdr(PsCEpAppHdr appHdr) {
		return psCEpAppHdrRepository.save(appHdr);
	}


	@Override
	public PsCEpAppRstVw getAppRst(String oprid, String year, String docid,
			String version) {
		PsCEpAppRstVwPrimary primary = new PsCEpAppRstVwPrimary();
		primary.setOprid(oprid);
		primary.setYear(year);
		primary.setVersion(new BigDecimal(version));
		primary.setcEpAppraisalId(docid);
		return psCEpAppRstVwRepository.findOne(primary);
	}


	@Override
	public PsCWfApelHdr saveApelHdr(PsCWfApelHdr apelHdr,PsCEpAppRstVw appRst,UserDTO user) {
		PsCWfApelHdr nowApelHdr = psCWfApelHdrRepository.findOne(apelHdr.getcTransactionNbr());
		if(nowApelHdr!=null){
			nowApelHdr.setcCommunication(apelHdr.getcCommunication());
			nowApelHdr.setcComnuniteDt(apelHdr.getcComnuniteDt());
			nowApelHdr.setcApplyItems(apelHdr.getcApplyItems());
			nowApelHdr.setcApplyReason(apelHdr.getcApplyReason());
			apelHdr =  psCWfApelHdrRepository.save(nowApelHdr);
		}else{
			JobCurrPrimary primary = new JobCurrPrimary();
			primary.setEmplid(user.getEmplId());
			primary.setEmplRcd(new BigDecimal(0));
			PsCWfEmpVw emp = psCWfEmpVwRepository.findOne(primary);//获取个人信息内容
			apelHdr.setCreatedttm(new Timestamp(System.currentTimeMillis())); // 创建时间
			apelHdr.setLastupddttm(new Timestamp(System.currentTimeMillis())); // 更新时间
			apelHdr.setcWfStatus(WfStatusEnum.WF_STATUS_S.getStatus()); // 流程状态
			apelHdr.setcWfType(WfTypeEnum.WF_STYPE_APEL.getType());// 流程类别
			apelHdr.setCreatedBy(user.getOprId()); // 创建人用户
			apelHdr.setLastupdoprid(user.getOprId()); // 更新者
			objectMapper.map(emp, apelHdr);//copy个人信息数据
			objectMapper.map(appRst, apelHdr);//copy绩效信息数据
			ObjectFieldUtils.handleNullValue(apelHdr);
			apelHdr =  psCWfApelHdrRepository.save(apelHdr);
		}
		return apelHdr;
	}


	@Override
	public void delApelHdr(String cTransactionNbr) {
		psCWfApelHdrRepository.delete(cTransactionNbr);
	}


	@Override
	public PsCWfApelHdr getApelHdr(String docid, BigDecimal version) {
		PsCWfApelHdr query = new PsCWfApelHdr();
		query.setcEpAppraisalId(docid);
		query.setVersion(version);
		List<PsCWfApelHdr> hdrs = psCWfApelHdrRepository.findAll(Example.of(query));
		if(hdrs!=null&&!hdrs.isEmpty()){
			return hdrs.get(0);
		}
		return null;
	}


	@Override
	public PsCWfApelHdr getApelHdr(String transnum) {
		return psCWfApelHdrRepository.findOne(transnum);
	}



	@Override
	public PsCWfApelHdr saveApelHdr(PsCWfApelHdr apelHdr) {
		return psCWfApelHdrRepository.save(apelHdr);
	}


	@Override
	public String getTempName(String templeId) {
		PsCEpTmplNmVw temp =  psCEpTmplNmVwRepository.findOne(templeId);
		if(temp!=null){
			return temp.getDescr();
		}
		return "";
	}

	@Override
	public String getGroupName(String groupId) {
		PsCEpRankGpVw gp = psCEpRankGpVwRepository.findOne(groupId);
		if(gp!=null){
			return gp.getDescr();
		}
		return "";
	}


	@Override
	public PsCEpIntrvwTbl getIntrvwTbl(String docid, BigDecimal version) {
		PsCEpAppHdrPrimary primary = new PsCEpAppHdrPrimary();
		primary.setcEpAppraisalId(docid);
		primary.setVersion(version);
		return psCEpIntrvwTblRepository.findOne(primary);
	}


	@Override
	@Transactional
	public PsCEpIntrvwTbl saveIntrvwTbl(PsCEpIntrvwTbl intrvwTbl, UserDTO user,String type) {
		PsCEpIntrvwTbl nowIntrvw =  getIntrvwTbl(intrvwTbl.getcEpAppraisalId(), intrvwTbl.getVersion());
		if(nowIntrvw!=null){
			nowIntrvw.setcEpCpbPlan(intrvwTbl.getcEpCpbPlan());
			nowIntrvw.setcEpDeficiencies(intrvwTbl.getcEpDeficiencies());
			nowIntrvw.setcEpImprPlan(intrvwTbl.getcEpImprPlan());
			nowIntrvw.setcEpReach(intrvwTbl.getcEpReach());
			nowIntrvw.setcEpReqHelp(intrvwTbl.getcEpReqHelp());
			if("commit".equals(type)){
				nowIntrvw.setcIntrvwStatus("I");
				intrvwTbl = psCEpIntrvwTblRepository.save(nowIntrvw);
				//调用提交service
				commitIntrvwService(intrvwTbl,null,user.getEmplId(), "SUB");
			}else{
				intrvwTbl = psCEpIntrvwTblRepository.save(nowIntrvw);
			}
		}else{
			//先生成审批角色内容
			saveTrvRoles(intrvwTbl);
			intrvwTbl.setcForceIntrvw("N");
			intrvwTbl.setcIntrvwStatus("P");
			if("commit".equals(type)){
				intrvwTbl.setcIntrvwStatus("I");
				intrvwTbl = psCEpIntrvwTblRepository.save(intrvwTbl);
				//调用提交service
				commitIntrvwService(intrvwTbl,null,user.getEmplId(), "SUB");
			}else{
				intrvwTbl = psCEpIntrvwTblRepository.save(intrvwTbl);
			}
		}
		return intrvwTbl;
	}
	
	
	public Map<String, String> commitIntrvwService(PsCEpIntrvwTbl intrvwTbl,BigDecimal seqnbr,String emplid,String action){
		StringBuilder soapXml = new StringBuilder();
		SoapXmlBuild.buildEpIntrvwRequest(soapXml,intrvwTbl.getcEpAppraisalId(),intrvwTbl.getVersion().toString(),seqnbr,emplid,action);
		String responXml = WebServiceClient.doPostSoap(processURL, soapXml.toString(), intrvwReqSoapAction);
		return WebServiceUtils.handleIntrvwReqRespXml(responXml,"C_EP_INTRVW_RES");
	}
	
	
	
	private void saveTrvRoles(PsCEpIntrvwTbl intrvwTbl){
		PsCEpTrvRole role;
		//查询数据
		PsCEpAppRVw2 query = new PsCEpAppRVw2();
		query.setcEpAppraisalId(intrvwTbl.getcEpAppraisalId());
		query.setVersion(intrvwTbl.getVersion());
		List<PsCEpAppRVw2> rvs = psCEpAppRVw2Repository.findAll(Example.of(query));
		if(rvs!=null&&!rvs.isEmpty()){
			for (PsCEpAppRVw2 rv : rvs) {
				if(!rv.getEmplid().equals(intrvwTbl.getEmplid())){
					role = new PsCEpTrvRole();
					role.setcEpAppraisalId(intrvwTbl.getcEpAppraisalId());
					role.setVersion(intrvwTbl.getVersion());
					role.setcEpRolename(rv.getcEpRolename());
					role.setcItrStatus("N");
					role.setCreatedttm(new Timestamp(System.currentTimeMillis()));
					role.setEmplid(rv.getEmplid());
					role.setEmplRcd(rv.getEmplRcd());
					role.setLastupddttm(new Timestamp(System.currentTimeMillis()));
					role.setSeqnbr(rv.getSeqnbr());
					psCEpTrvRoleRepository.save(role);
				}
			}
		}
	}


	@Override
	public List<List<PsCEpTrvRole>> getIntrvwProcessMap(String docid,
			BigDecimal version) {
		PsCEpTrvRole query = new PsCEpTrvRole();
		query.setcEpAppraisalId(docid);
		query.setVersion(version);
		List<PsCEpTrvRole> trvRoles = psCEpTrvRoleRepository.findAll(Example.of(query));
		if(trvRoles!=null&&!trvRoles.isEmpty()){
			Map<Integer, List<PsCEpTrvRole>> respVOMap = new TreeMap<Integer, List<PsCEpTrvRole>>(new MapKeyComparator());
			List<PsCEpTrvRole> respVoList;
			for (PsCEpTrvRole trvRole : trvRoles) {
				if(respVOMap.containsKey(trvRole.getSeqnbr().intValue())){
					respVOMap.get(trvRole.getSeqnbr().intValue()).add(trvRole);
				}else{
					respVoList = new ArrayList<PsCEpTrvRole>();
					respVoList.add(trvRole);
					respVOMap.put(trvRole.getSeqnbr().intValue(), respVoList);
				}
			}
			List<List<PsCEpTrvRole>> respVOlists = new ArrayList<List<PsCEpTrvRole>>(respVOMap.values());
			return respVOlists;
		}
		return null;
	}
	
	
	
	
	
	public class MapKeyComparator implements Comparator<Integer>{
	    @Override
	    public int compare(Integer int1, Integer int2) {
	        return int1.compareTo(int2);
	    }
	}

	@Override
	public PsCEpTrvRole getEpTrvRoles(String docid, BigDecimal version,String emplid) {
		PsCEpTrvRole query = new PsCEpTrvRole();
		query.setcEpAppraisalId(docid);
		query.setVersion(version);
		List<PsCEpTrvRole> roles =  psCEpTrvRoleRepository.findAll(Example.of(query));
		if(roles!=null&&!roles.isEmpty()){
			for (PsCEpTrvRole role : roles) {
				if(emplid.equals(role.getEmplid())){
					return role;
				}
			}
		}
		return null;
	}
}
 